package com.zxy.supplier_system.server.configuration

import com.zxy.supplier_system.server.service.WechatUserInfoService
import com.zxy.supplier_system.server.utils.wechat.mini.WechatMiniProgramHelper
import com.zxy.supplier_system.server.utils.wechat.official.WechatOfficialAccountHelper
import com.zxy.supplier_system.server.utils.wechat.official.WechatServerConfig
import com.zxy.supplier_system.server.utils.wechat.official.getAllFollowers
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.scheduling.annotation.EnableScheduling
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component

@Configuration
@EnableConfigurationProperties(value = [WechatProperties::class])
class WechatConfiguration {

    @Bean
    fun wechatMiniProgramHelper(wechatProperties: WechatProperties): WechatMiniProgramHelper {
        return WechatMiniProgramHelper(wechatProperties.mini.appId, wechatProperties.mini.appSecret)
    }

    @Bean
    fun wechatOfficialAccountHelper(wechatProperties: WechatProperties): WechatOfficialAccountHelper {
        return WechatOfficialAccountHelper(wechatProperties.official.appId, wechatProperties.official.appSecret,wechatProperties.official.serverMessage.let {
            WechatServerConfig(it.token, it.encodingAESKey)
        })
    }

}

@EnableScheduling
@Component
class WechatScheduling(
    private val wechatOfficialAccountHelper: WechatOfficialAccountHelper,
    private val wechatUserInfoService: WechatUserInfoService,
) {

    @Scheduled(fixedDelay = 1000 * 60 * 30)
    fun fetchOfficialAccountFollowers() {
        wechatUserInfoService.fetchAndUpdateOfficialAccountFollowers(wechatOfficialAccountHelper.getAllFollowers())
    }

}


@ConfigurationProperties(prefix = "wechat")
class WechatProperties(
    val pay: Pay,
    val official: Official,
    val mini: Mini,
    val app: App,

    ) {
    class Pay(
        val merchantCASerialNumber: String,
        val merchantId: String,
        val apiV3Key: String,
    )

    class Mini(
        val appId: String,
        val appSecret: String
    )

    class Official(
        val appId: String,
        val appSecret: String,
        val messageTemplates: MessageTemplates,
        val serverMessage: ServerMessage
    ) {
        class MessageTemplates(
            val waitAuditMarketOrder: String,
            val auditedMarketOrder: String,

            )

        class ServerMessage(
            val token: String,
            val encodingAESKey: String
        )
    }

    class App(
        val appId: String
    )


}
